package com.easylinkin.linkappapi.lobar.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.easylinkin.linkappapi.annotation.CommonOperateLogAnnotate;
import com.easylinkin.linkappapi.common.model.RequestModel;
import com.easylinkin.linkappapi.common.utils.excel.ExcelConstant;
import com.easylinkin.linkappapi.common.utils.excel.ExcelTools;
import com.easylinkin.linkappapi.common.utils.io.OutputStreamUtil;
import com.easylinkin.linkappapi.lobar.dto.*;
import com.easylinkin.linkappapi.lobar.entity.WarningConfig;
import com.easylinkin.linkappapi.lobar.service.WarningService;
import com.easylinkin.linkappapi.lobar.vo.*;
import com.easylinkin.linkappapi.operatelog.constant.LogConstant;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import site.morn.rest.RestBuilders;
import site.morn.rest.RestMessage;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author: kan yuanfeng
 * @Date: 2020/11/04 11:42
 * @Description: 预警管理
 */
@RestController
@RequestMapping("warning")
@Api(tags = "预警管理")
public class WarningController {

  @Autowired
  private WarningService warningService;

  /**
   * @Description: 根据条件，分页(不分页)查询人员出勤预警
   * @author kan yuanfeng
   * @date 2020/11/04 11:42
   */
  @PostMapping("userWarning")
  @ApiOperation("根据条件，分页(不分页)查询人员出勤预警")
  public RestMessage queryUserWarning(@RequestBody RequestModel<UserWarningDTO> requestModel){
    Assert.notNull(requestModel.getCustomQueryParams(), "customQueryParams 不能为空");
    Assert.notNull(requestModel.getPage(), "page 不能为空");
    IPage<UserWarningDTO> record =  warningService.queryUserWarning(requestModel);
    return RestBuilders.successBuilder().data(record).build();
  }

  /**
   * @Description: 根据条件，导出
   * @author kan yuanfeng
   * @date 2020/11/04 11:42
   */
  @PostMapping("export")
  @ApiOperation("根据条件，导出")
  @CommonOperateLogAnnotate(module = LogConstant.LogModule.LABOR_MANAGEMENT, desc = "导出健康管理报表")
  public void export(@RequestBody RequestModel<UserWarningDTO> requestModel, HttpServletRequest request, HttpServletResponse response) {
    requestModel.getPage().setSize(-1);
    List<UserWarningDTO> list = new ArrayList<>();
    IPage<UserWarningDTO> record =  warningService.queryUserWarning(requestModel);
    Map<String, List<UserWarningDTO>> listMap = record.getRecords().stream().collect(Collectors.groupingBy(UserWarningDTO::getUserId));
    listMap.forEach((k,v) ->{
      //按时间排序
      List<UserWarningDTO> dtoList = v.stream().sorted(Comparator.comparing(UserWarningDTO::getCreateTime).reversed()).collect(Collectors.toList());
      UserWarningDTO warningDTO = dtoList.get(0);
      setWarningStr(warningDTO);
//      处理状态(1已处理 0未处理)
      list.add(warningDTO);
    });

    List<UserWarningDTO> dtoList = list.stream().sorted(Comparator.comparing(UserWarningDTO::getCreateTime).reversed()).collect(Collectors.toList());
    String keyValue = "姓名:userName,身份证号:idCard,参建单位:companyName,班组:groupName,"
            + "工种:workType,联系电话:telephone,连续未出勤天数:warningRuleStr,状态:statusStr,处理时间:handleTime";
    String title = "连续未出勤人员名单";
    String fileName = title + ".xls";
    try {
      OutputStream outputStream = OutputStreamUtil
              .getOutputStream(request, response, fileName);
      ExcelTools.exportExcel(outputStream, keyValue, dtoList, ExcelConstant.XLS, title);
      response.flushBuffer();
      outputStream.close();
    } catch (IOException e) {
      throw new RuntimeException("excel导出失败！IOException异常" + e.getMessage());
    } catch (Exception e) {
      throw new RuntimeException("excel导出失败！" + e.getMessage());
    }
  }

  /**
   * @Description: 根据条件，分页(不分页)查询疫情监测预警
   * @author xy
   * @date 2022/08/16 15:55
   */
  @PostMapping("epidemicWarning")
  @ApiOperation("根据条件，分页(不分页)查询疫情监测预警")
  public RestMessage queryEpidemicWarning(@RequestBody RequestModel<EpidemicWarningDTO> requestModel){
    Assert.notNull(requestModel.getCustomQueryParams(), "customQueryParams 不能为空");
    Assert.notNull(requestModel.getPage(), "page 不能为空");
    IPage<EpidemicWarningDTO> record =  warningService.queryEpidemicWarning(requestModel);
    return RestBuilders.successBuilder().data(record).build();
  }

  /**
   * @Description: 根据条件，分页(不分页)查询班组出勤预警
   * @author kan yuanfeng
   * @date 2020/11/04 11:42
   */
  @PostMapping("groupWarning")
  @ApiOperation("根据条件，分页(不分页)查询班组出勤预警")
  public RestMessage queryGroupWarning(@RequestBody RequestModel<GroupWarningDTO> requestModel){
    Assert.notNull(requestModel.getCustomQueryParams(), "customQueryParams 不能为空");
    Assert.notNull(requestModel.getPage(), "page 不能为空");
    IPage<GroupWarningDTO> record =  warningService.queryGroupWarning(requestModel);
    return RestBuilders.successBuilder().data(record).build();
  }

  /**
   * @Description: 根据条件，分页(不分页)查询年龄预警
   * @author kan yuanfeng
   * @date 2020/11/04 11:42
   */
  @PostMapping("ageWarning")
  @ApiOperation("根据条件，分页(不分页)查询年龄预警")
  public RestMessage queryAgeWarning(@RequestBody RequestModel<AgeWarningDTO> requestModel){
    Assert.notNull(requestModel.getCustomQueryParams(), "customQueryParams 不能为空");
    Assert.notNull(requestModel.getPage(), "page 不能为空");
    IPage<AgeWarningDTO> record =  warningService.queryAgeWarning(requestModel);
    return RestBuilders.successBuilder().data(record).build();
  }

  /**
   * @Description: 根据条件，分页(不分页)查询证书预警
   * @author kan yuanfeng
   * @date 2020/11/04 11:42
   */
  @PostMapping("certificateWarning")
  @ApiOperation("根据条件，分页(不分页)查询证书预警")
  public RestMessage queryCertificateWarning(@RequestBody RequestModel<CertificateWarningDTO> requestModel){
    Assert.notNull(requestModel.getCustomQueryParams(), "customQueryParams 不能为空");
    Assert.notNull(requestModel.getPage(), "page 不能为空");
    IPage<CertificateWarningDTO> record =  warningService.queryCertificateWarning(requestModel);
    return RestBuilders.successBuilder().data(record).build();
  }

  /**
   * @Description: 查询预警设置(没有设置的查询默认设置)
   * @author kan yuanfeng
   * isDefault 等于true 查询初始默认值
   * @date 2020/11/04 11:42
   */
  @GetMapping("warningConfig")
  @ApiOperation("查询预警设置(没有设置的查询默认设置)")
  public RestMessage queryWarningConfig(Boolean isDefault){
    WarningConfig warningConfig =  warningService.queryWarningConfig(isDefault);
    return RestBuilders.successBuilder().data(warningConfig).build();
  }

  /**
   * @Description: 设置预警参数
   * @author kan yuanfeng
   * @date 2020/11/04 11:42
   */
  @PostMapping("warningConfig")
  @ApiOperation("设置预警参数")
  @CommonOperateLogAnnotate(module = LogConstant.LogModule.LABOR_MANAGEMENT, desc = "编辑预警设置")
  public RestMessage updateWarningConfig(@RequestBody WarningConfigDTO warningConfig){
    warningService.updateWarningConfig(warningConfig);
    return RestBuilders.successBuilder().build();
  }

  /**
   * 人员预警批量处理
   *
   * @param userWarningVo 人员预警vo
   * @return 统一出参
   */
  @PostMapping("/userWarningBatchOperate")
  @ApiOperation("人员预警批量处理")
  public RestMessage userWarningBatchOperate(@RequestBody UserWarningVo userWarningVo) {
    return warningService.userWarningBatchOperate(userWarningVo);
  }

  /**
   * 年龄预警批量处理
   *
   * @param ageWarningVo 年龄预警vo
   * @return 统一出参
   */
  @PostMapping("/ageWarningBatchOperate")
  @ApiOperation("年龄预警批量处理")
  public RestMessage ageWarningBatchOperate(@RequestBody AgeWarningVo ageWarningVo) {
    return warningService.ageWarningBatchOperate(ageWarningVo);
  }

  /**
   * 证书预警批量处理
   *
   * @param certificateWarningVo 证书预警vo
   * @return 统一出参
   */
  @PostMapping("/certificateWarningBatchOperate")
  @ApiOperation("证书预警批量处理")
  public RestMessage certificateWarningBatchOperate(@RequestBody CertificateWarningVo certificateWarningVo) {
    return warningService.certificateWarningBatchOperate(certificateWarningVo);
  }

  /**
   * 获取证书预警记录对应的证书信息
   *
   * @param id 证书告警id
   * @return 统一出参
   */
  @GetMapping("/getWarningCertificateInfo/{id}")
  @ApiOperation("获取证书预警记录对应的证书信息")
  public RestMessage getWarningCertificateInfo(@PathVariable String id) {
    return warningService.getWarningCertificateInfo(id);
  }

  /**
   * 证书预警记录更新证书
   *
   * @param certificateWarningVo 证书告警vo
   * @return 统一出参
   */
  @PostMapping("/certificateWarningUploadCert")
  @ApiOperation("证书预警记录更新证书信息")
  public RestMessage certificateWarningUploadCert(@RequestBody CertificateWarningVo certificateWarningVo) {
    return warningService.certificateWarningUploadCert(certificateWarningVo);
  }
  /**
   * 班组出勤预警批量处理
   *
   * @param groupWarningVo 班组出勤预警vo
   * @return 统一出参
   */
  @PostMapping("/groupWarningBatchOperate")
  @ApiOperation("班组出勤预警批量处理")
  public RestMessage groupWarningBatchOperate(@RequestBody GroupWarningVo groupWarningVo) {
    return warningService.groupWarningBatchOperate(groupWarningVo);
  }

  /**
   * 疫情监测预警信息批量处理
   *
   * @param epidemicWarningVo 疫情监测预警vo
   * @return 统一出参
   */
  @PostMapping("/epidemicWarningBatchOperate")
  @ApiOperation("疫情监测预警信息批量处理")
  public RestMessage epidemicWarningBatchOperate(@RequestBody EpidemicWarningVo epidemicWarningVo) {
    return warningService.epidemicWarningBatchOperate(epidemicWarningVo);
  }

  /**
   * 人员进出场预警列表
   *
   * @param requestModel 入参
   * @return 统一出参
   * @Description: 根据条件，分页(不分页)查询人员出场预警
   */
  @PostMapping("/userOutinWarning")
  @ApiOperation("根据条件，分页(不分页)查询人员出场预警")
  public RestMessage queryUserOutinWarning(@RequestBody RequestModel<UserOutinWarningDTO> requestModel) {
    Assert.notNull(requestModel.getCustomQueryParams(), "customQueryParams 不能为空");
    Assert.notNull(requestModel.getPage(), "page 不能为空");
    IPage<UserOutinWarningDTO> record = warningService.queryUserOutinWarning(requestModel);
    return RestBuilders.successBuilder().data(record).build();
  }

  /**
   * 人员进出场预警批量处理
   *
   * @param userOutinWarningVo 人员进出场预警vo
   * @return 统一出参
   */
  @PostMapping("/userOutinWarningBatchOperate")
  @ApiOperation("人员进出场预警批量处理")
  public RestMessage userOutinWarningBatchOperate(@RequestBody UserOutinWarningVo userOutinWarningVo) {
    return warningService.userOutinWarningBatchOperate(userOutinWarningVo);
  }

  /**
   * 设置规则字符串
   */
  private void setWarningStr(UserWarningDTO warningDTO){
//    <div>{{row.warningRule.split(" ").length>1?row.warningRule.split(" ")[3]:row.warningRule.split(" ")[0]}}</div>
    String warningRule = warningDTO.getWarningRule();
    String s = null;
    if (StringUtils.isNotBlank(warningRule)){
      String[] split = warningRule.split(" ");
      if (split.length > 1){
        s = split[3];
      }else {
        s = split[0];
      }
      //替换 自动退场 预警
      s = s.replaceAll("自动退场",StringUtils.EMPTY).replaceAll("预警",StringUtils.EMPTY);
    }
    warningDTO.setWarningRuleStr(s);
    //设置状态 处理状态(1已处理 0未处理)
    warningDTO.setStatusStr(Integer.valueOf(1).equals(warningDTO.getStatus())?"已处理":"未处理");
  }

}

